package com.hae.shop.micoshopproductservice.controller;

import com.hae.shop.common.base.Response;
import com.hae.shop.micoshopproductservice.reposiory.ProductReposiory;
import com.hae.shop.micoshopproductservice.reposiory.model.ProductEntity;
import com.hae.shop.product.api.ProductService;
import com.hae.shop.product.model.ProductDto;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Validated
public class ProductServiceController implements ProductService {

    @Autowired
    private ProductReposiory productReposiory;

    @Override
    @PostMapping("/searchGoods")
    public Response<List<ProductDto>> searchGoods(@RequestParam("key") String key) {
        Response<List<ProductDto>> response = new Response<>();
        // 构建ES查询参数
        BoolQueryBuilder builder = QueryBuilders.boolQuery();
        builder.must(QueryBuilders.multiMatchQuery(key, "name", "subtitle","detail")); //多字段检索
        Pageable pageable = new QPageRequest(0, 5);
        // 执行查询
        Page<ProductEntity> page = productReposiory.search(builder, pageable);
        // 封装查询结果
        List<ProductEntity> content = page.getContent();
        MapperFactory mapperFactory = new DefaultMapperFactory.Builder().build();
        List<ProductDto> mapAsList = mapperFactory.getMapperFacade().mapAsList(content, ProductDto.class);
        response.setResult(mapAsList);
        return response;
    }
}
